//
//  ConfirmSendGoodsCtr-ext.swift
//  smosky
//
//  Created by zhuxietong on 2018/8/8.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation
import Eelay
import soapp
import AsyncDisplayKit

extension ConfirmSendGoodsCtr{
    class PushSelectorField:FieldView {
        let valueL = UILabel()
        let indicatorV = UIImageView()
        override func addLayoutRules() {
            let bt = UIButton()
            eelay = [
                [indicatorV,[ee.Y.R,[0,-8]],"14",14],
                [valueL,[ee.L.Y,[0,0]],[indicatorV,ee.L,ee.R,-4]],
                [bt,[ee.T.L.B.R]],
            ]
            indicatorV.image = UIImage(named:"house_indicator_n")
            valueL.ui.font(font: FieldView.holderStyle.font).text(color: FieldView.holderStyle.color)
            bt.addTarget(self, action: #selector(gotoSelect), for: .touchUpInside)
        }
        
        var selector = FmPushTypeSelector()
        
        @objc func gotoSelect(){
            weak var wself = self
            selector.confirmSelect = {
                obj in
                //                wself?.fillData(data: obj)
                //                print("===dUUUUU|\(obj)")
                
                let id = obj["id",""]
                wself?.mo.model["value"] = obj.rawJson ?? "{}"
                wself?.mo.model["value_display"] = obj["name",""]
                
                wself?.mo_model_reload()
                let field = wself?.putItem()?._ID ?? ""
                __post(notify: FK.Notice.valueChange, object: wself?.controller, userInfo: ["value": id,FK.field:field])
                
            }
            self.controller?.navigationController?.pushViewController(selector, animated: true)
        }
        
        override func mo_model_reload() {
            let display = mo.model["value_display",""]
            if display.len > 0{
                valueL.ui.font(font: valueFont).text(color: valueColor).text(display)
            }
            else{
                valueL.ui.font(font: holderFont).text(color: holderColor).text(place_holder)
            }
        }
        
    }
    
    class FmPushTypeSelector:TypeInitController,UITableViewDelegate,UITableViewDataSource
    {
        let tableView = UITableView(frame: .zero, style: .plain)
        
        override var initTopStyle: EeTopStyle{
            return ___shop.top_nav
        }
        class Cell: JoCheckedCell {
            let titleL = UILabel()
            let infoL = UILabel()
            let indicatorV = UIImageView()
            override func addLayoutRules() {
                contentView.eelay = [
                    [titleL,[ee.T.L.B.R,[15,AppTheme.edge,-15,-AppTheme.edge]],"20"],
                    //                    [__line,[ee.L.B.R],"\(TP.separatorHeight)"]
                ]
                //                __line.backgroundColor = UIColor.separator_color
                //                self.accessoryType = .checkmark
                _ = titleL.ui.font14.cl_444.left
                _ = infoL.ui.font10.cl_888.left
            }
            override func updateIsChecked() {
                if isChecked
                {
                    accessoryType = .checkmark
                }
                else{
                    accessoryType = .none
                }
            }
            
            override func mo_model_reload() {
                //                titleL.text = mo.model["body.title",""]
                titleL.text = mo.model["name",""]
                //                infoL.text = "昆明市 官渡区"
                
                self.isChecked = mo.model[FK.selected,FK.NO] == FK.YES
            }
        }
        
        var currentSeletedObj:NSMutableDictionary? = nil
        {
            didSet{
                oldValue?[FK.selected] = FK.NO
            }
        }
        var confirmSelect:(NSMutableDictionary)->Void = {_ in}
        
        override func viewDidLoad() {
            super.viewDidLoad()
            tableView.delegate = self
            tableView.dataSource = self
            jo_contentView.eelay = [
                [tableView,[ee.T.L.B.R]]
            ]
            
            title = "选择物流公司".loc
            tableView.register(Cell.self, forCellReuseIdentifier: "cell")
            tableView.register(Header.self, forHeaderFooterViewReuseIdentifier: "header")
            tableView.tintColor = ___shop.second
            tableView.separatorColor = UIColor.separator_color
            tableView.buildDynamicHeight(height: 50)
            mo_request_send()
            
        }
        
        var sections:NSMutableArray = NSMutableArray(){
            didSet{
                
            }
        }
        
        var indexs:[String] = [String]()
        var houseList = NSMutableArray()
        {
            didSet{
                var titles = [String]()
                houseList.listObj { (one:NSMutableDictionary) in
                    titles.append(one["name",""])
                }
                //
                //                let section = ChineseSortSections.create(names: titles, mapObjects: houseList as! [Any])
                //                self.sections = DataNode.path(node: "childs", section.0.data, value: NSMutableArray())
                //                self.indexs = section.1
                self.indexs = titles
                self.sections = houseList
                tableView.reloadData()
                
                //                let indexs = ChineseString.indexArray(titles) ?? NSMutableArray()
                //                print("++++++|||\(section.data)")
            }
        }
        
        
        override func mo_request_send() {
            weak var wself = self
            loadingV.loading()
            
            JoTask().get.log._surl(.物流公司查询).json_handle { (status, msg, obj, resp) in
                wself?.loadingV.dismiss()
                if status.isSuccess{
                    if let list = obj as? NSMutableArray{
                        //                        let list = DataNode.path(node: "list", dict, value: NSMutableArray())
                        wself?.houseList = list
                        return
                    }
                }
                wself?.mo_request_alert()
                }.run()
        }
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            let one_section = DataNode.path(node: "\(section).list", sections, value: NSMutableArray())
            return one_section.count
        }
        
        func numberOfSections(in tableView: UITableView) -> Int {
            return sections.count
        }
        
        func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
            let cell = tableView.cellForRow(at: indexPath) as? Cell
            cell?.isChecked = false
        }
        
        
        
        
        
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let data = DataNode.path(node: "\(indexPath.section).list.\(indexPath.row)", sections, value:NSMutableDictionary())
            currentSeletedObj = data
            confirmSelect(data)
            let cell = tableView.cellForRow(at: indexPath) as? Cell
            cell?.isChecked = true
            
            navigationController?.popViewController(animated: true)
        }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! Cell
            let data = DataNode.path(node: "\(indexPath.section).list.\(indexPath.row)", sections, value:NSMutableDictionary())
            cell.mo.model = data
            return cell
        }
        
        
        
        func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 30
        }
        
        
        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") as? Header
            let key_section = DataNode.path(node: "\(section)", sections, value: NSMutableDictionary())
            
            header?.titleL.text = key_section["name",""]
            return header
        }
        
        func sectionIndexTitles(for tableView: UITableView) -> [String]? {
            return indexs
        }
        
        
    }
    
    
    class Header: JoHeaderFooterView {
        let titleL = UILabel()
        override func addLayoutRules() {
            contentView.eelay = [
                [titleL,[ee.T.L.B.R,[8,10,-8,-10]],"14"]
            ]
            contentView.backgroundColor = UIColor.table_bg_color
        }
    }

}
